﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace ProjectQuaDep
{
    public partial class CheckLiked : System.Web.UI.Page
    {
        bool liked = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            //pageLike();
        }

        public bool ValidateSignedRequest()
        {
            var VALID_SIGNED_REQUEST = Request.Form["signed_request"];

            string applicationSecret = "4a33f90ee8569d0e581c69f787203ca1";
            string[] signedRequest = VALID_SIGNED_REQUEST.Split('.');
            string expectedSignature = signedRequest[0];
            string payload = signedRequest[1];

            // Attempt to get same hash
            var Hmac = SignWithHmac(UTF8Encoding.UTF8.GetBytes(payload), UTF8Encoding.UTF8.GetBytes(applicationSecret));
            var HmacBase64 = ToUrlBase64String(Hmac);

            return (HmacBase64 == expectedSignature);
        }

        private string ToUrlBase64String(byte[] Input)
        {
            return Convert.ToBase64String(Input).Replace("=", String.Empty)
                                                .Replace('+', '-')
                                                .Replace('/', '_');
        }

        private byte[] SignWithHmac(byte[] dataToSign, byte[] keyBody)
        {
            using (var hmacAlgorithm = new HMACSHA256(keyBody))
            {
                hmacAlgorithm.ComputeHash(dataToSign);
                return hmacAlgorithm.Hash;
            }
        }

        public Dictionary<string, string> DecodePayload(string payload)
        {
            //Remove the bad part of signed_request
            //Begin
            string[] sB64String = payload.Split('.');
            payload = payload.Replace((sB64String[0] + "."), string.Empty);
            //End
            var encoding = new UTF8Encoding();
            var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
            var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
            var json = encoding.GetString(base64JsonArray);
            var jObject = JObject.Parse(json);
            var parameters = new Dictionary<string, string>();

            parameters.Add("page", ((bool)jObject["page"]["liked"]).ToString());
            parameters.Add("admin", ((bool)jObject["page"]["admin"]).ToString());
            return parameters;


        }

        protected void pageLike()
        {

            string pageLiked = string.Empty;
            if (ValidateSignedRequest())
            {
                var signed_request = Request.Form["signed_request"];
                if (!String.IsNullOrEmpty(signed_request))
                {
                    //string payload = signed_request.Split('.')[1];
                    //var encoding = new UTF8Encoding();
                    //var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
                    //var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
                    //var json = encoding.GetString(base64JsonArray);
                    //JObject obj = JObject.Parse(json);
                    //liked = (bool)obj.SelectToken("page.liked");

                    var json = DecodePayload(signed_request);
                    foreach (KeyValuePair<string, string> objKVP in json)
                    {
                        //Note You can also see if a user is an admin by replacing the objKVP.Key with admin
                        if (objKVP.Key == "page" && objKVP.Value == "True")
                        {
                            Response.Redirect("https://www.YOURSITE.com/facebook/app/pageLiked.aspx");
                            //litJson.Text += objKVP.Key + " - " + objKVP.Value + "<br />";
                        }
                    }
                }
            }
        }
    }
}